import java.util.Scanner;

/**
 * @author: gao
 * @create-date: 2025/3/24 16:27
 */
class ListNode{
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public ListNode reverseBetween(ListNode head,int right,int left){
        if(head == null || left == right){
            return head;
        }
        //创建虚拟头节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        //找到反转区间的前一个结点
        ListNode pre = dummy;
        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }

        ListNode cur = pre.next;

        //反转指定区间
        for (int i = 0; i < right - left; i++) {
            ListNode tmp = cur.next;
            cur.next = tmp.next;
            tmp.next = pre.next;
            pre.next = tmp;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode newHead = solution.reverseBetween(node1,4,2);
        System.out.println();
    }
}